﻿using System;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Collections.Generic;
using System.Web;

namespace Findy.XsltDb
{
    public static class ReflectionTools
    {
        private static Regex PropertyPathSplitter = new Regex(@"(?<!\[[^\]]*)\.", RegexOptions.Compiled);
        private static Regex IndexerSplitter = new Regex(@"(.*?)\[(.*?)\]", RegexOptions.Compiled);
        public static object GetPropertyValue(object obj, string name)
        {
            string[] parts = PropertyPathSplitter.Split(name);
            foreach (string part in parts)
            {
                if (obj != null)
                {
                    Match m = IndexerSplitter.Match(part);
                    if (m.Success)
                    {
                        string prop = m.Groups[1].Value;
                        string index = m.Groups[2].Value;
                        obj = new PF(obj, prop).GetValue(obj);
                        if ( obj != null )
                            obj = new PF(obj, "this").GetValue(obj, index);
                    }
                    else
                        obj = new PF(obj, part).GetValue(obj);
                }
            }
            if (obj == null)
                return string.Empty; //XSLT extensions can't return null

            return obj;
        }

        public static void SetPropertyValue(object obj, string name, object value)
        {
            SetPropertyValue(obj, null, name, value);
        }
        public static void SetPropertyValue(object obj, Type type, string name, object value)
        {
            string[] parts = PropertyPathSplitter.Split(name);
            for (int i = 0; i < parts.Length - 1; i++)
            {
                if (obj != null)
                {
                    Match m = IndexerSplitter.Match(parts[i]);
                    if (m.Success)
                    {
                        string prop = m.Groups[1].Value;
                        string index = m.Groups[2].Value;
                        obj = new PF(obj, prop).GetValue(obj);
                        if ( obj != null )
                            obj = new PF(obj, "this").GetValue(obj, index);
                    }
                    else
                        obj = new PF(obj, parts[i]).GetValue(obj);
                }
            }
            if (obj == null)
                return;

            Match mL = IndexerSplitter.Match(parts[parts.Length - 1]);
            if (mL.Success)
            {
                string prop = mL.Groups[1].Value;
                string index = mL.Groups[2].Value;
                obj = new PF(obj, prop).GetValue(obj);
                new PF(obj, "this").SetValue(obj, value, index);
                return;
            }
            new PF(obj, parts[parts.Length-1]).SetValue(obj,value);
        }

        class PF
        {
            PropertyInfo pi;
            FieldInfo fi;
            public PF(object obj, string Name) : this(obj, null, Name) { }
            public PF(object obj, Type type, string Name)
            {

                if (type == null)
                    type = obj.GetType();
                if (Name == "this")
                    pi = GetItemProperty(obj, type, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
                else
                {
                    pi = type.GetProperty(Name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
                    fi = type.GetField(Name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
                }

                if (pi == null && fi == null)
                {
                    if (Name == "this")
                        pi = GetItemProperty(obj, type, BindingFlags.Public | BindingFlags.Instance);
                    else
                    {
                        pi = type.GetProperty(Name, BindingFlags.Public | BindingFlags.Instance);
                        fi = type.GetField(Name, BindingFlags.Public | BindingFlags.Instance);
                    }
                }

                if (pi == null && fi == null)
                    throw new Exception(string.Format("Can't find property '{0}' for the type '{1}'.", Name, type.FullName));
            }

            private PropertyInfo GetItemProperty(object obj, Type type, BindingFlags flags)
            {
                foreach (PropertyInfo i in type.GetProperties(flags))
                {
                    ParameterInfo[] indexes = i.GetIndexParameters();
                    if (indexes.Length == 1 &&
                        (indexes[0].ParameterType == typeof(string) || indexes[0].ParameterType == typeof(object)))
                        return i;
                }
                return null;
            }

            public void SetValue(object obj, object v) { SetValue(obj, v, null); }
            public void SetValue(object obj, object v, object index)
            {
                object v2;
                try
                {
                    v2 = Convert.ChangeType(v, this.Type);
                }
                catch (Exception)
                {
                    v2 = this.Type.GetConstructor(new Type[] { typeof(string) }).Invoke(new object[] { v.ToString() });
                }

                if (pi != null)
                    pi.SetValue(obj, v2, index != null ? new object[] { index } : null);
                if (fi != null)
                    fi.SetValue(obj, v2);
            }
            public object GetValue(object obj) { return GetValue(obj, null); }
            public object GetValue(object obj, object index)
            {
                if (fi != null)
                    return fi.GetValue(obj);
                if (pi != null)
                    return pi.GetValue(obj, index != null ? new object[] { index } : null);
                return string.Empty;
            }
            public Type Type
            {
                get {
                    return fi != null ? fi.FieldType: pi.PropertyType;
                }
            }
        }
    }
}
